package xframe.util.db;

import java.sql.Connection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class Transaction
{

    public Transaction()
    {
    }

    public static void start(HttpServletRequest request)
        throws Exception
    {
        Connection con = (Connection)request.getAttribute("CONNECTION");
        if(con != null && !con.isClosed())
        {
            con = DBConnector.getConnection();
            //dbConnectionCnt++;
            //System.out.println("������ ��� �翬��:" + dbConnectionCnt);
        } else
        {
            con = DBConnector.getConnection();
            dbConnectionCnt++;
            //System.out.println("��� ���� ��:" + dbConnectionCnt);
        }
        con.setAutoCommit(false);
        request.setAttribute("CONNECTION", con);
    }

    public static void end(HttpServletRequest request)
    {
        try
        {
            Connection con = (Connection)request.getAttribute("CONNECTION");
            if(con != null && !con.isClosed())
            {
                dbConnectionCnt--;
                //System.out.println("���� close() ��" + dbConnectionCnt);
                con.commit();
                con.close();
                request.setAttribute("CONNECTION", null);
            }
        }
        catch(Exception e)
        {
            System.out.println(e);
            e.printStackTrace();
        }
    }

    public static void rollback(HttpServletRequest request, HttpServletResponse response)
    {
        try
        {
            Connection con = (Connection)request.getAttribute("CONNECTION");
            if(con != null && !con.isClosed())
            {
                con.rollback();
                con.close();
                request.setAttribute("CONNECTION", null);
                dbConnectionCnt--;
                System.out.println("rollback  DB close() :" + dbConnectionCnt);
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
            request.setAttribute("ERROR_MSG", e.toString());
        }
    }

    public static int dbConnectionCnt = 0;

}
